<?php

namespace App\Services;


use App\Enum\MonitorEnum;
use App\Models\MonitorModel;
use Illuminate\Support\Facades\Log;


class MonitorService
{
    private const LATEST_FETCH_NUM=1;
    private const MP_CONTENT='USER_ID=%d, CONTENT=%s';

    /**
     * 获取最新的监控数据
     *
     * @param $lastId
     * @param int $type
     * @return array|false
     */
    public static function getLatestMonitor($lastId, int $type=MonitorEnum::MONITOR_TYPE_ALL)
    {
        $model = MonitorModel::query()->where('id','>', $lastId)->where('status',MonitorEnum::MONITOR_STATUS_NO);
        if( $type !== MonitorEnum::MONITOR_TYPE_ALL )
            $model = $model->where(['type',$type]);
        $result = $model->orderBy('id')->limit(self::LATEST_FETCH_NUM)->get(['id','name','status','memo','created_at']);
        if( empty($result) ) return false;
        return $result->toArray();
    }

    /**
     * 添加 自动分配承运商的监控
     * @param $content
     * @return void
     */
    public static function addDispatchTransportException($content){
        self::addException(MonitorEnum::MONITOR_TYPE_DISPATCH_TRANSPORT,$content);
    }

    /**
     * 添加订单创建成功后的监控
     *
     * @param $content
     * @return void
     */
    public static function addOrderCreatedException($content){
        self::addException(MonitorEnum::MONITOR_TYPE_ORDER_CREATED,$content);
    }
    public static function addException( $type, $content )
    {
        $data = [
            'name'=>MonitorEnum::MONITOR_TYPE_NAMES[$type],
            'type'=>$type,
            'memo'=>$content,
            'status'=>MonitorEnum::MONITOR_STATUS_NO
        ];
        MonitorModel::create($data);
    }
    public static function addMpException($userId, $content)
    {
        self::addException(MonitorEnum::MONITOR_TYPE_MP_EXCEPTION, sprintf(self::MP_CONTENT, $userId, $content) );
    }
}
